//
//  ActivityListViewController.m
//  金融
//
//  Created by Apple on 2018/1/3.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "ActivityListViewController.h"
#import "ActivityWebViewController.h"
#import "ActivityDetailViewController.h"
#import "ActivityCell.h"

static NSString * cellID = @"ActivityCellID";
@interface ActivityListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView    * tableView;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, assign) NSInteger         page;
@property (nonatomic, assign) BOOL              hasMore;
@end

@implementation ActivityListViewController

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"ActivityCell" bundle:nil] forCellReuseIdentifier:cellID];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    }
    return _tableView;
}
- (void)footerRefresh
{
    if (self.hasMore) {
        self.page ++;
        [self networking];
    }
}
- (void)networking
{
    WeakSelf
    NSDictionary * dict = @{@"page":[NSNumber numberWithInteger:self.page],@"size":[NSNumber numberWithInteger:10],@"data":@{}};
    [HttpRequest postWithURLString:HOST(@"app/activity/list") parameters:dict showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.dataArray addObjectsFromArray:responseObject[@"data"][@"content"]];
            if (weakSelf.page >= [responseObject[@"data"][@"totalPages"] integerValue] ) {
                weakSelf.hasMore = NO;
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                weakSelf.tableView.mj_footer.hidden = YES;
                weakSelf.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            }
            if (weakSelf.dataArray.count > 0) {
                weakSelf.tableView.hidden = NO;
                weakSelf.NoDataView.hidden = YES;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView reloadData];
                });
            }else{
                weakSelf.tableView.hidden = YES;
                weakSelf.NoDataView.hidden = NO;
            }
        }
        [weakSelf.tableView.mj_footer endRefreshing];
    } failure:^(NSError * _Nullable error) {
        weakSelf.tableView.hidden = YES;
        weakSelf.NoDataView.hidden = NO;
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        weakSelf.tableView.mj_footer.hidden = YES;
    }login:^(BOOL isLogin) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf ShowLoginView];
        });
    }];
}
- (void)ShowLoginView
{
    HFLoginView * logView = [HFLoginView shareInit];
    [logView show];
    WeakSelf
    logView.clickPushBlock = ^(NSInteger index) {
        if (index == 0) {
            [weakSelf PushRigest];
        }else{
            [weakSelf PushLogin];
        }
    };
}
- (void)PushRigest
{
    RegisterViewController * rc = [[RegisterViewController alloc] init];
    rc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:rc animated:YES];
}
- (void)PushLogin
{
    LoginViewController * lgvc = [[LoginViewController alloc] init];
    lgvc.myClass = NSStringFromClass([self class]);
    WeakSelf
    lgvc.LoginSuccessBlock = ^{
        [weakSelf reloadCusData];
    };
    lgvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:lgvc animated:YES];
}
- (void)reloadCusData
{
    [self.dataArray removeAllObjects];
    self.page = 1;
    self.hasMore = YES;
    [self networking];
}
- (void)setNavBar
{
    [self.barView addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.barView);
        make.width.mas_greaterThanOrEqualTo(10);
        make.height.mas_greaterThanOrEqualTo(10);
    }];
    self.titleL.text = @"活动中心";
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavBar];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.barView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }else{
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadCusData)];
    [self reloadCusData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ActivityCell * cell = [[ActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setDataWithDict:self.dataArray[indexPath.section] index:indexPath.section];
    WeakSelf
    cell.clickHotAction = ^(NSInteger index) {
        NSInteger type = [weakSelf.dataArray[indexPath.section][@"type"] integerValue];
        [weakSelf pushType:type index:index];
    };
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150 * SizeWidth + 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section == self.dataArray.count - 1){
        return 0.01f;
    }
    return 10.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}
- (void)pushType:(NSInteger)type index:(NSInteger)index
{
    if(type == 0){
        ActivityDetailViewController * ad = [[ActivityDetailViewController alloc] init];
        ad.activityID = self.dataArray[index][@"id"];
        [self.navigationController pushViewController:ad animated:YES];
    }else{
        ActivityWebViewController * aw = [[ActivityWebViewController alloc] init];
        aw.cusTitle = self.dataArray[index][@"title"];
        NSString * urlStr = [NSString stringWithFormat:@"%@?token=%@",self.dataArray[index][@"url"],[HFUser getSaveToken]];
        aw.url = [NSURL URLWithString:urlStr];
        [self.navigationController pushViewController:aw animated:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
